package com.xuesinuo.ots.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import com.google.common.io.ByteSink;
import com.google.common.io.Files;

public class FileUtil {

    /** 获取文件名后缀 */
    public static String getSuffix(String fileName) {
        if (fileName == null || fileName.isBlank()) {
            return null;
        }
        int indexOfPoint = fileName.lastIndexOf(".");
        if (indexOfPoint == -1) {
            return null;
        }
        return fileName.substring(indexOfPoint + 1);
    }

    /** 从inputStream写入文件 */
    public static void writeFromInputStreamAndClose(InputStream inputStream, File file) {
        ByteSink byteSink = Files.asByteSink(file);
        try {
            if (!file.exists()) {
                FileUtil.createFileWithParentDirs(file.getAbsolutePath());
            }
            byteSink.writeFrom(inputStream);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /** 获取文件，如果不存在，则递归创建文件夹与文件 */
    public static File createFileWithParentDirs(String filePath) {
        File file = new File(filePath);
        try {
            Files.createParentDirs(file);
            file.createNewFile();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return file;
    }
}
